#include "mat_animation_mgr.h"

#include "util/common_macros.h"		// macros


MATAnimationManager::~MATAnimationManager()
{
	for( int i = 0; i < (int) m_Animations.size(); i++)
	{
		UTIL_SAFE_DELETE(m_Animations[i]);
		
	}
}


MATAnimationManager&	MATAnimationManager::Instance()
{
	static MATAnimationManager inst;
	return inst;
}


void					MATAnimationManager::Tick(float dt)
{
	for( int i = 0; i < (int) m_Animations.size(); i++)
	{
		m_Animations[i]->Tick(dt);
		
	}

}


MATAnimation*			MATAnimationManager::AddAnimation(int y, int x, MATGem* pGemType, MATAnimation::ANI_TYPE AniType)
{
	if(!pGemType)
		return NULL;

	MATAnimation* pActive = GetActiveAnimAt(y,x);
	if(pActive && !pActive->IsFinish())
	{
		//return NULL;
		//pActive->ForceFinish();
	}

	for( int i = 0; i < (int) m_Animations.size(); i++)
	{
		if( m_Animations[i]->GetType() == AniType && m_Animations[i]->IsFinish() )
		{
			// found unused
			m_Animations[i]->Init(y,x,pGemType);
			return m_Animations[i];
		}
	}

	// create new
	MATAnimation* pAni = NULL;
	switch(AniType)
	{
		case MATAnimation::ANI_TYPE_SMALLTOBIG:
			pAni = new MATAniSmallTobig();				
				break;

		case MATAnimation::ANI_TYPE_MATCHED:
			pAni = new MATAniMatched();
			break;

		case MATAnimation::ANI_TYPE_MOVING:
			pAni = new MATAniMoving();
			break;

		default: 
			pAni = NULL;
			break;
	}

	if(pAni)
	{
		pAni->Init(y,x,pGemType);
		m_Animations.push_back(pAni);
	}

	return pAni;
}


MATAnimation*			MATAnimationManager::GetActiveAnimAt(int y, int x)
{
	for( int i = 0; i < (int) m_Animations.size(); i++)
	{
		if( m_Animations[i]->GetX() == x && m_Animations[i]->GetY() == y && m_Animations[i]->IsFinish() == false )
		{
			
			return m_Animations[i];
		}
	}
	return NULL;
}


bool	MATAnimationManager::IsActiveAnimation(MATAnimation::ANI_TYPE AnimationType)
{
	for( int i = 0; i < (int) m_Animations.size(); i++)
	{
		if( m_Animations[i]->GetType() == AnimationType && !m_Animations[i]->IsFinish() )
		{
			return true;
		}
	}
	return false;
}

void	MATAnimationManager::ForceFinish()
{
	for( int i = 0; i < (int) m_Animations.size(); i++)
	{
		m_Animations[i]->ForceFinish();
	}
	
}